<?php


/**
* CakePHP Routines Plugin
* http://cake-routines-plugin.googlecode.com
*
* @package routines
* @subpackage routines.models.behaviors
* @author Ivan Chistyakov <zetruger@gmail.com>
* @version $Id: dividable.php 167 2010-10-22 07:13:36Z zetruger@gmail.com $
* @link $HeadURL: http://cake-routines-plugin.googlecode.com/svn/trunk/models/behaviors/dividable.php $
* @license MIT License (http://opensource.org/licenses/mit-license.php)
*/


class DividableBehavior extends ModelBehavior {

var $_defaults = array(
	'dividField' => 'divider',
	'dividValue' => NULL,
	'useRequestParams' => TRUE,
	'useRequestNamedParams' => FALSE
);

var $settings = array();

function setup(&$Model, $settings = array()) {
	$this->settings[$Model->alias] = $settings;
}

function _getSettings(&$Model, $settings = array()) {
	if (!empty($Model->useTable) && (Inflector::tableize($Model->alias) != $Model->useTable)) {
		$this->_defaults['dividValue'] = $Model->alias;
	}
	$settings = Set::merge($this->settings[$Model->alias], $settings);
	if (isset($settings['noUseModelVars']) && $settings['noUseModelVars']) {
		return Set::merge($this->_defaults, $settings);
	} else {
		return Set::merge($this->_defaults, array_intersect_key(get_object_vars($Model), $this->_defaults), $settings);
	}
}

function _getRequestSettings(&$Model, $settings = array()) {
	extract($settings = $this->_getSettings($Model), EXTR_SKIP);
	$requestParams = Router::getParams(TRUE);
	if (Inflector::tableize($Model->alias) == $requestParams['controller']) {
		if ($useRequestParams && isset($requestParams[$dividField])) {
			$settings['dividValue'] = $requestParams[$dividField];
		} elseif ($useRequestNamedParams && isset($requestParams['named'][$dividField])) {
			$settings['dividValue'] = $requestParams['named'][$dividField];
		}
	}
	return $settings;
}

function beforeFind(&$Model, $query) {
	extract($this->_getRequestSettings($Model), EXTR_SKIP);
	if ($Model->hasField($dividField) && !is_null($dividValue)) {
		$query['conditions'][$Model->escapeField($dividField)] = $dividValue;
	}
	return $query;
}

function beforeSave(&$Model) {
	extract($this->_getRequestSettings($Model), EXTR_SKIP);
	if ($Model->hasField($dividField) && !is_null($dividValue)) {
		$Model->data[$Model->alias][$dividField] = $dividValue;
	}
	return TRUE;
}

}


?>